﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace iNet.IO
{
	/// <summary>
	/// 檔案路徑比較元件。
	/// </summary>
	public class PathComparer : IComparer<string>, IEqualityComparer<string>, IEqualityComparer
	{
		#region 欄位
		/// <summary>
		/// 預設的執行個體。
		/// </summary>
		public static readonly PathComparer Default = new PathComparer();
		bool _IgnoreCase;
		#endregion
		#region 建構子
		/// <summary>
		/// 初始化新的 PathComparer 執行個體。
		/// </summary>
		public PathComparer()
		{
			switch (Environment.OSVersion.Platform)
			{
				case PlatformID.Win32NT:
				case PlatformID.Win32S:
				case PlatformID.Win32Windows:
				case PlatformID.WinCE:
					_IgnoreCase = true;
					break;
			}
		}
		#endregion
		#region Compare
		/// <summary>
		/// 比較兩個檔案路徑。
		/// </summary>
		/// <param name="pathA">第一個檔案路徑。</param>
		/// <param name="pathB">第二個檔案路徑。</param>
		/// <returns>比路徑較結果。</returns>
		public int Compare(string pathA, string pathB)
		{
			return string.Compare(pathA, pathB, _IgnoreCase);
		}
		#endregion
		#region Equals
		/// <summary>
		/// 比較兩個路徑是否相同。
		/// </summary>
		/// <param name="pathA">第一個路徑。</param>
		/// <param name="pathB">第二個路徑。</param>
		/// <returns>兩個路徑是否相同。</returns>
		public bool Equals(string pathA, string pathB)
		{
			return string.Compare(pathA, pathB, _IgnoreCase) == 0;
		}
		#endregion
		#region GetHashCode
		/// <summary>
		/// 取得路徑的雜湊碼。
		/// </summary>
		/// <param name="path">檔案路徑。</param>
		/// <returns>路徑的雜湊碼。</returns>
		public int GetHashCode(string path)
		{
			//確認
			if (path == null)
				throw new ArgumentNullException("path");

			//回傳
			if (_IgnoreCase)
				return path.ToLower().GetHashCode();
			return path.GetHashCode();
		}
		#endregion
		#region IEqualityComparer.Equals
		bool IEqualityComparer.Equals(object x, object y)
		{
			if (x == null)
				return y == null;
			if (x is string)
			{
				if (y is string)
					return string.Compare(x as string, y as string, _IgnoreCase) == 0;
			}
			return false;
		}
		#endregion
		#region IEqualityComparer.GetHashCode
		int IEqualityComparer.GetHashCode(object obj)
		{
			if (obj == null)
				throw new ArgumentNullException("obj");
			if (!(obj is string))
				throw new ArgumentException("傳入的物件不是一個字串。");
			if (_IgnoreCase)
				return (obj as string).ToLower().GetHashCode();
			return (obj as string).GetHashCode();
		}
		#endregion
		#region IgnoreCase
		/// <summary>
		/// 取得值以確認是否忽略路徑字元的大小寫。
		/// </summary>
		public bool IgnoreCase
		{
			get
			{
				return _IgnoreCase;
			}
		}
		#endregion
	}
}